<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-09-22
 * Time: 9:27:09
 * Info: 邮件模板类模型
 */

namespace plugin\email\app\model;

use app\common\model\Common;
use think\facade\Db;

class Template extends Common
{

    const TEMPLATE_OPTION_PREFIX = 'email_template_';

    /**
     * 获取模板
     *
     * @param $templateName
     *
     * @return array
     */
    public static function findData($templateName)
    {
        $dataValue = Db::name('plugin_email_template')->where(['name' => static::templateNameToOptionName($templateName)])->find();

        return $dataValue ?? [];
    }

    public static function saveData($templateName, $from, $subject, $content)
    {
        $data = [
            'name'        => static::templateNameToOptionName($templateName),
            'from'        => $from,
            'subject'     => $subject,
            'content'     => $content,
            'create_time' => time(),
            'update_time' => time(),
        ];
        Db::name('plugin_email_template')->data($data)->insert();
    }

    /**
     * 模版名到option名转换
     *
     * @param string $templateName
     *
     * @return string
     */
    public static function templateNameToOptionName(string $templateName): string
    {
        return self::TEMPLATE_OPTION_PREFIX.$templateName;
    }

    /**
     * option名到模版名转换
     *
     * @param string $optionName
     *
     * @return string
     */
    public static function optionNameToTemplateName(string $optionName): string
    {
        return substr($optionName, strlen(self::TEMPLATE_OPTION_PREFIX));
    }

    /**
     * 删除模版
     *
     * @param array $templateNames
     *
     * @return void
     */
    public static function deleteTemplate($templateIds)
    {
        Db::name('plugin_email_template')->whereIn('id', $templateIds)->delete();
    }

}
